package it.fuesi.expired.api.controllers;

import it.fuesi.expired.adapters.base.IAdapterSession;
import it.fuesi.expired.api.AttachmentService;
import it.fuesi.expired.api.controllers.base.ACrudController;
import it.fuesi.expired.model.Attachment;
import it.fuesi.expired.model.base.ErrorModel;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class AttachmentController extends ACrudController<Attachment> implements AttachmentService{

	
	@RequestMapping(method = RequestMethod.GET, value = BASE_URI + "/{_id}")
	@ResponseBody
	public byte[] getFile(@PathVariable String _id) throws Exception{
		return adapter.openSession().getFile(_id);
	}
	
	@RequestMapping(method = RequestMethod.POST, value = BASE_URI)
	@ResponseBody
	public Attachment putFile(@RequestParam(value="data") MultipartFile data, @RequestParam(value="attachment", required=false) Attachment att) throws Exception{
		if(att == null){
			att = new Attachment();
			att.setFileName(data.getName());
			att.setFileSize(data.getSize());
		}
		
		return adapter.openSession().putFile(att, data.getBytes());
	}
	
	@RequestMapping(method = RequestMethod.DELETE, value = BASE_URI + "/{_id}")
	@ResponseBody
	public ErrorModel deleteFile(@PathVariable String _id) throws Exception{
		IAdapterSession session = null;
		final ErrorModel error = new ErrorModel();
		error.set_id(_id);
		try{
			session = adapter.openSession();
			
			session.deleteFile(_id);
			
			error.setSuccess(true);
		}finally{
			if(session != null)
				session.close();
		}
		
		return error;
		
	}
	
	@RequestMapping(method = RequestMethod.DELETE, value = BASE_URI + "/clean")
	@ResponseBody
	public ErrorModel cleanFiles() throws Exception{
		IAdapterSession session = null;
		final ErrorModel error = new ErrorModel();
		try{
			session = adapter.openSession();
			
			session.cleanFiles();
			
			error.setSuccess(true);
		}finally{
			if(session != null)
				session.close();
		}
		
		return error;
		
	}
	
	
	
	
}
